package com.example.demo.controller;

import com.example.demo.emailCode.emailCode;
import com.example.demo.entity.User;
import com.example.demo.result.R;
import com.example.demo.result.Renum;
import com.example.demo.service.UserService;
import com.example.demo.utils.RUtils;
import com.example.demo.sms.sendMessage;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/User")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    @Qualifier("redisTemplate")
    //实例化
    private RedisTemplate<Object, Object> rts;

    private Integer userId;

    //用户列表
    @ResponseBody
    @RequestMapping(value = "/getUserList",method = RequestMethod.GET)
    List<User> getUserList(){
        return userService.getUserList();
    }

    //用户信息
    @CrossOrigin
    @ResponseBody
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd hh:mm:ss")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @RequestMapping("/getUserById")
    public R getUserById(Integer userId){
        User user = userService.getById(userId);
        System.out.println(user.getUserBirthday());
        return RUtils.success(userService.getById(userId));
    }

    //验证码
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/check")
    public R check(String userPhoneNum) {
        System.out.println(userPhoneNum);
        String checknum = "";
        List<User> users = userService.getUserList();
        for(User user: users) {
            if(userPhoneNum.equals(user.getUserPhoneNum())) {
                return RUtils.error(Renum.USER_IS_EXISTS);
            }
        }
        boolean b = Pattern.matches("1\\d{10}", userPhoneNum);    //如果b为true 则为手机号
        if (!b) return RUtils.error(Renum.ACCOUNT_ERROR);
        checknum = sendMessage.sendSMS(userPhoneNum);
        System.out.println("验证码为： "+checknum);
        //将手机号和验证码存入redis,生存时间为5分钟
        rts.opsForValue().set(userPhoneNum,checknum,5, TimeUnit.MINUTES);
        return RUtils.success(Renum.SUCCESS);
    }

    //注册
    @CrossOrigin
    @ResponseBody
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd hh:mm:ss")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @RequestMapping("/register")
    public R addUser(String userPhoneNum, String checkCode,String userPassword){
        User user = new User();
        Object code=rts.opsForValue().get(userPhoneNum);
        if(checkCode.equals(code)) {
            user.setUserPhoneNum(userPhoneNum);
            user.setUserPassword(userPassword);
            user.setUserName("默认名称");
            Date date = new Date(System.currentTimeMillis());
            user.setUserLoginDate(date);
            userService.addUser(user);
            return RUtils.success(Renum.SUCCESS);
        }
        return RUtils.error(Renum.CHECK_CODE_ERROR);
    }

    @CrossOrigin
    @ResponseBody
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd hh:mm:ss")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @RequestMapping("/login")
    /*   密码错误     登录成功返回用户ID   账户不存在*/
    public R login(String userPhoneNum, String userPassword){
        List<User> users = userService.getUserList();
        String message;
        boolean flag = false;
        for(User user: users){
            if(userPhoneNum.equals(user.getUserPhoneNum())){
                if(userPassword.equals(user.getUserPassword())){
                    Date date = new Date(System.currentTimeMillis());
                    user.setUserLoginDate(date);
                    userService.updateUserLoginDate(user.getUserId(),date);
                    return RUtils.success(userService.getById(user.getUserId()));
                }
                flag = true; //密码错误
            }
        }
        if(flag)
            return RUtils.error(Renum.USER_PWD_ERROR);
        return RUtils.error(Renum.USER_NOT_EXIST);
    }

    @ResponseBody
    @RequestMapping("/deleteUserById")
    //通过userId删除用户
    public String deleteUserById(Integer userId){
        userService.deleteById(userId);
        return "删除用户成功";
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/setUserInfo")
    public R setUserInfo(Integer userId, String name, String introduce, String birthday) throws ParseException {

        java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = formatter.parse(birthday);
        if(userService.setUserInformation(userId,name,introduce,date)>0)
            return RUtils.success(Renum.SUCCESS);
        return RUtils.error(Renum.ERROR);
    }


    //找回密码验证码
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/checkFind")
    public R checkFind(String userPhoneNum) {
        System.out.println(userPhoneNum);
        String checknum1 = "";
        List<User> users = userService.getUserList();
        boolean b = Pattern.matches("1\\d{10}", userPhoneNum);    //如果b为true 则为手机号
        if (!b) return RUtils.error(Renum.ACCOUNT_ERROR);
        int flag=0;//标记用户是否存在
        for(User user: users) {
            if(userPhoneNum.equals(user.getUserPhoneNum())) {
                userId=user.getUserId();
                checknum1 = sendMessage.sendSMS(userPhoneNum);
                System.out.println("验证码为： "+checknum1);
                //将手机号和验证码存入redis,生存时间为5分钟
                rts.opsForValue().set(userPhoneNum,checknum1,5, TimeUnit.MINUTES);
                flag=1;
            }
        }
         if(flag==0) {
             return RUtils.error(Renum.USER_NOT_EXIST);
         }
        return RUtils.success(Renum.SUCCESS);
    }

    //更换手机号验证码
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/changePhoneCode")
    public R changePhoneCode(String userPhoneNum) {
        System.out.println(userPhoneNum);
        String checknum1 = "";
        List<User> users = userService.getUserList();
        boolean b = Pattern.matches("1\\d{10}", userPhoneNum);    //如果b为true 则为手机号
        if (!b) return RUtils.error(Renum.ACCOUNT_ERROR);
        int flag=0;//标记用户是否存在
        for(User user: users) {
            if(userPhoneNum.equals(user.getUserPhoneNum())) {
                flag=1;
            }
        }
        if(flag==0) {
            checknum1 = sendMessage.sendSMS(userPhoneNum);
            System.out.println("验证码为： "+checknum1);
            //将手机号和验证码存入redis,生存时间为5分钟
            rts.opsForValue().set(userPhoneNum,checknum1,5, TimeUnit.MINUTES);
            return RUtils.success(Renum.SUCCESS);
        }else {
            return RUtils.error(Renum.USER_IS_EXISTS);
        }
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/updatePasswordByPhone")
    //忘记密码
    public R updatePassswordByPhone(Integer userId,String userPhoneNum,String checkCode, String userPassword1,String userPassword2) {
        User user=new User();
        Object code=rts.opsForValue().get(userPhoneNum);
        if(checkCode.equals(code)){
            if(userPassword1.equals(userPassword2)){
                userService.updatePwd(userId,userPassword2);
                return RUtils.success(Renum.SUCCESS);
            }
            else{
                return RUtils.error(Renum.TWO_PASSWORD_ERROR);
            }
        }
        else{
            return RUtils.error(Renum.CHECK_CODE_ERROR);
        }
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/updatePasswordByMail")
    //更改密码
    public R updatePasswordByMail(Integer userId,String userMail,String code,String userPassword1,String userPassword2) {
        User user=new User();
        Object checkcode=rts.opsForValue().get(userMail);
        if(code.equals(checkcode)){
            if(userPassword1.equals(userPassword2)){
                userService.updatePwd(userId,userPassword2);
                return RUtils.success(Renum.SUCCESS);
            }
            else{
                return RUtils.error(Renum.TWO_PASSWORD_ERROR);
            }
        }
        else{
            return RUtils.error(Renum.CHECK_CODE_ERROR);
        }
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/mailCode")
    //获取邮箱验证码
    public R mailCode(String userMail){
        System.out.println(userMail);
        String checkcode="";
        List<User> users = userService.getUserList();
        boolean b = Pattern.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", userMail);//如果b为true，则为邮箱号
        if(!b) return RUtils.error(Renum.ACCOUNT_ERROR);
        checkcode = emailCode.sendCode(userMail);
        System.out.println("验证码为："+checkcode);
        rts.opsForValue().set(userMail,checkcode,5, TimeUnit.MINUTES);
        return RUtils.success(Renum.SUCCESS);
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/changeMailCode")
    //更换邮箱验证码
    public R changeMailCode(String userMail){
        System.out.println(userMail);
        String checkcode="";
        List<User> users = userService.getUserList();
        boolean b = Pattern.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", userMail);//如果b为true，则为邮箱号
        if(!b) return RUtils.error(Renum.ACCOUNT_ERROR);
        int flag=0;//标记用户是否存在
        for(User user: users) {
            if(userMail.equals(user.getUserMail())) {
                flag=1;
            }
        }
        if(flag==0) {
            checkcode = emailCode.sendCode(userMail);
            System.out.println("验证码为："+checkcode);
            rts.opsForValue().set(userMail,checkcode,5, TimeUnit.MINUTES);
            return RUtils.success(Renum.SUCCESS);
        }else {
            return RUtils.error(Renum.USER_IS_EXISTS);
        }
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/bindEmail")
    //绑定邮箱
    public R bindEmail(Integer userId,String userMail,String mailCode){
        User user=new User();
        Object checkcode=rts.opsForValue().get(userMail);
        if(mailCode.equals(checkcode)) {
            userService.bindEmailAddress(userId,userMail);
            return RUtils.success(Renum.SUCCESS);
        }else {
            return RUtils.error(Renum.CHECK_CODE_ERROR);
        }
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/verifyCode")
    //验证验证码
    public R verifyCode(String code,String phoneOrMail){
        Object checkcode=rts.opsForValue().get(phoneOrMail);
        if(code.equals(checkcode)){
            return RUtils.success(Renum.SUCCESS);
        } else {
            return RUtils.error(Renum.CHECK_CODE_ERROR);
        }

    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/changePhone")
    //更改手机号
    public R changePhone(Integer userId,String userPhoneNum){
        userService.updatePhone(userId,userPhoneNum);
        return RUtils.success(Renum.SUCCESS);
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/changeMail")
    //通过邮箱更改邮箱
    public R changeMail(Integer userId,String userMail){
        userService.updateMail(userId,userMail);
        return RUtils.success(Renum.SUCCESS);
    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/changePassWordByOldPass")
    public R changePassword(Integer userId ,String oldPassword, String newPassword){
        User user = userService.getById(userId);
        String old = user.getUserPassword();
        if(!old.equals(oldPassword)){
            return RUtils.error(Renum.USER_PWD_ERROR);
        }else{
            int num = userService.updatePassword(userId, newPassword);
            if(num == 1){
                return RUtils.success(Renum.SUCCESS);
            }else return RUtils.error(Renum.UNKNOWN_ERROR);

        }

    }

}
